#-*- codeing = utf-8 -*-
#@Time :2021/8/20 20:41
#@Author :邓龙
#@File :preservation.py
#@Software: PyCharm

import pandas as pd
import os
from sqlalchemy import create_engine
# 初始化数据库连接，使用pymysql模块
# MySQL的用户：root, 密码:root, 端口：3306,数据库中已存在的数据库名：lianjia
engine = create_engine(r'mysql+pymysql://root:root@47.108.73.57:3306/lianjia?serverTimezone=UTC')
def write_sql(name,data=pd.DataFrame()):
    global engine
    data.to_sql(name,engine,if_exists='fail',index=False)

# 数据路径（csv文件）
path = r'cd_info.csv'
# 表示读取path下的文件夹‘仅用于学习测试数据’的第一条数据，
# 读取全部可将后面的[0]去掉，下面的[name_list]---》变成name_list，item.split('.')[0]---》item.split('.')
name_list = os.listdir(path)[1]

for item in [name_list]:

    name = item.split('.')[0]
    path_ = os.path.join(path,item)
    print(path_)
    with open(path_, 'rb') as f:
        data = pd.read_csv(f, sep=',', header=0, index_col=None, na_values=['NULL'], na_filter=True, encoding='utf8')
        write_sql(name,data)

print('完成！')